package util.string;

import java.util.regex.Pattern;

public class URLCleaner {

	/**
	 * 
	 * clean url and trim the url at the level specify by the argument 'level'
	 * 
	 * e.g, www.google/something/something2.html
	 * 
	 * with level = 1
	 * 
	 * google/something
	 * 
	 *with level =0
	 * 
	 * google
	 * 
	 * 
	 * @param url
	 */

	public static String simplifyURL(String url, int level) {

		url = cleanURL(url);

		if(url.endsWith("/")){
			
			url = url.substring(0,url.length()-1);
		
		}
		
		int index_previous = url.indexOf("/");
		
		if (index_previous <= 0) {

			return url;
		}

		int index=0;
		
		for (int i = 0; i < level; i++) {
			
			index = url.indexOf("/", index_previous+1);
			
			if (index < 0) {

				return new String(url);
			}
			
			index_previous=index;

		}

		if(index_previous>0 && index_previous<url.length()){	
			
			url = url.substring(0,index_previous);
			
		}
		return new String(url);

	}
	
	public static String fallBack(String url, int level) {

		url = cleanURL(url);

		if(url.endsWith("/")){
			
			url = url.substring(0,url.length()-1);
		}
		int index_previous = url.lastIndexOf("/");

		if (index_previous <= 0) {

			return url;
		}

		int index=0;
		String url_temporal=url;
		for (int i = 0; i < level; i++) {
			
			index = url_temporal.lastIndexOf("/");
			
			if (index < 0) {
				
				return url_temporal;
			}
			url_temporal= (String) url_temporal.subSequence(0,index);
			

		}

		return  new String(url_temporal);

	}

	public static String cleanURL(String object) {
		// TODO Auto-generated method stub

		object = object.toLowerCase().trim();
		object = object.replace("www.", "");
		object = object.replace("http://", "");
		object = object.replace("https://", "");

		
		return  new String(object);
	}

	public static void main(String argsp[]) {
		String url ="http://littlekids.nationalgeographic.com/littlekids/animals/giant-panda-grows-up-2.html";
		Pattern matcher = Pattern.compile("^youtube.com.*");
		System.out.println(matcher.matcher("youtube.com/buenas/tardes/asdfas.php?sdfadf").matches());
		System.out.println(URLCleaner.simplifyURL(url, 1));
		System.out.println(URLCleaner.fallBack(url,2));
		

	}

}